import { contractList, projectAdd, projectDetail, projectUpdate } from "@/services/chargingManage";
import { businessConfigs } from "@/services/workOrder";
import { getUuid } from "@/utils/utils";
import { Button, Cascader, DatePicker, Form, Input, message, Modal, Select } from "antd";
import moment from "moment";
import React from "react";
import { formatMessage } from 'umi-plugin-react/locale';
const dateFormat = 'YYYY-MM-DD'

class ProjectModal extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      visible:false,
      id:null,
      products:[],
      productNameIds:[[]],
      contractOptions:[],
      consultant:[{id:getUuid(),value:""}]
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  initModal = id => {
    this.getProducts()
    this.getContractList()
    this.setState({
      id,
      visible:true
    },async () => {
      if(id){
        this.getDetail()
      }
    })
  }

  getContractList = async () => {
    const res = await contractList({current:1,size:9999,enterpriseId:this.props.enterpriseId})
    this.setState({contractOptions:res.records})
  }

  getProducts = async () => {
    const res = await businessConfigs()
    this.setState({products:res.products})
  }

  getDetail = async () => {
    const res = await projectDetail({id:this.state.id})
    this.props.form.setFieldsValue({
      name:res.name,
      planTimes:[moment(res.planStartTime),moment(res.planEndTime)],
      realTimes:[moment(res.realStartTime),moment(res.realEndTime)],
      contractIds:res.contractIds
    })
    const consultant = res.consultant.map(item =>  {
      return {id:getUuid(),value:item}
    })
    this.setState({
      productNameIds:res.productNameIds,
      consultant
    })
  }

  doCancel = () => {
    this.props.form.resetFields()
    this.setState({
      visible:false,
      id:null,
      productNameIds:[[]],
      consultant:[{id:getUuid(),value:""}]
    })
  }

  okValidate = () => {
    this.props.form.validateFields(((error,values) => {
      if(!error){
        this.doSubmit(values)
      }
    }))
  }

  doSubmit = async values => {
    const { id,productNameIds ,consultant} = this.state
    let res = {}
    let {planTimes,realTimes,...obj} = values;
    
    obj = {...obj,
      planStartTime:values.planTimes && values.planTimes[0] ? moment(values.planTimes[0]).format(dateFormat) : '',
      planEndTime:values.planTimes && values.planTimes[1] ? moment(values.planTimes[1]).format(dateFormat) : '',
      realStartTime:values.realTimes && values.realTimes[0] ? moment(values.realTimes[0]).format(dateFormat) : '',
      realEndTime:values.realTimes && values.realTimes[1] ? moment(values.realTimes[1]).format(dateFormat) : '',
      productNameIds,
      consultant:consultant.map(item => item.value),
      enterpriseId:this.props.enterpriseId
    }

    if(id){
      obj.id = id
      res = await projectUpdate(obj)
    }else{
      res = await projectAdd(obj)
    }

    if(res.code === -1){return false}

    message.info(res.message)
    this.doCancel()
    this.props.refreshList()
  }

  onChange= (value,index,field) => {
    let list = this.state[field]
    list[index] = value;
    this.setState({[field]:list})
  }

  addItem = (value,field) => {
    let list = this.state[field]
    list.push(value)
    this.setState({[field]:list})
  }

  deleteItem = (index,field) => {
    let list = this.state[field]
    const newList = list.filter((item,i) => i!= index)
    this.setState({[field]:newList})
  }

  changeValue = (e,index) => {
    let { consultant } = this.state;
    consultant[index].value = e.target.value
    this.setState({consultant})
  }

  render(){
    const { visible ,products,productNameIds,contractOptions,consultant} = this.state;
    const { form:{getFieldDecorator} } = this.props
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
    };
    return(
      <Modal
        title={formatMessage({ id: 'projectModal.title' })}
        visible={visible}
        onCancel={this.doCancel}
        onOk={this.okValidate}
        width={700}
      >
        <Form {...formItemLayout}>
          <Form.Item label={formatMessage({ id: 'projectModal.form.name' })}>
            {getFieldDecorator("name",{rules:[{required:true,message:formatMessage({ id: 'projectModal.form.pleaseInput' })}]})(
              <Input />
            )}
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'projectModal.form.productName' })}>
            {
              productNameIds.map((item,index) => {
                return (
                  <div style={{marginBottom:10}} key={getUuid()} >
                    <Cascader 
                      value={item} 
                      options={products} 
                      onChange={(value) => this.onChange(value,index,'productNameIds')} 
                      placeholder={formatMessage({ id: 'projectModal.form.pleaseSelect' })} 
                      style={{width:400,marginRight:10}} 
                      fieldNames={{ label: 'name', value: 'name' }}
                    />
                    {
                      index === 0 ? <Button size="small" ghost type="primary" onClick={() => this.addItem([],'productNameIds')}>{formatMessage({ id: 'projectModal.button.add' })}</Button> : <Button size="small" ghost type="danger" onClick={() => this.deleteItem(index,'productNameIds')}>{formatMessage({ id: 'projectModal.button.delete' })}</Button>
                    }
                    
                  </div>
                )
              })
            }
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'projectModal.form.contract' })}>
            {getFieldDecorator("contractIds",{rules:[{required:true,message:formatMessage({ id: 'projectModal.form.pleaseInput' })}]})(
              <Select mode="multiple">
                {
                  contractOptions.map(item => {
                    return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                  })
                }
              </Select>
            )}
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'projectModal.form.consultant' })}>
            {
              consultant.map((item,index) => {
                return (
                  <div style={{marginBottom:10}} key={item.id} >
                    <Input style={{width:400,marginRight:10}} value={item.value} onChange={e => this.changeValue(e,index)} />
                    {
                      index === 0 ? <Button size="small" ghost type="primary" onClick={() => this.addItem({id:getUuid(),value:""},'consultant')}>{formatMessage({ id: 'projectModal.button.add' })}</Button> : <Button size="small" ghost type="danger" onClick={() => this.deleteItem(index,'consultant')}>{formatMessage({ id: 'projectModal.button.delete' })}</Button>
                    }
                  </div>
                )
              })
            }
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'projectModal.form.planDateRange' })}>
            {getFieldDecorator("planTimes",{rules:[{required:true,message:formatMessage({ id: 'projectModal.form.pleaseSelect' })}]})(
              <DatePicker.RangePicker />
            )}
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'projectModal.form.realDateRange' })}>
            {getFieldDecorator("realTimes",{rules:[{required:true,message:formatMessage({ id: 'projectModal.form.pleaseSelect' })}]})(
              <DatePicker.RangePicker />
            )}
          </Form.Item>
        </Form>
      </Modal>
    )
  }
}

export default Form.create()(ProjectModal)